package co.edu.udem.dao.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import co.edu.udem.dao.NotificationDao;
import co.edu.udem.domain.Notification;
import co.edu.udem.domain.SubjectDetail;

@Repository("notificationDao")
@Transactional
public class NotificationDaoImpl implements NotificationDao {

	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	public List<Notification> getAllNotifications() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("FROM  Notification");
		return query.list();
	}

	public Notification getNotificationById(Integer id) {
		Session session = sessionFactory.getCurrentSession();
		Notification notification = (Notification) session.get(
				Notification.class, id);
		return notification;
	}

	public void saveNotification(Notification notification) {
		Session session = sessionFactory.getCurrentSession();
		session.merge(notification);
	}

	public void deleteNotification(Integer id) {
		Session session = sessionFactory.getCurrentSession();
		Notification notification = (Notification) session.get(
				Notification.class, id);
		session.delete(notification);
	}

	public int getValidUuid() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session
				.createQuery("Select MAX (n.uuid) FROM  Notification n");
		Integer value = (Integer) query.uniqueResult();
		return value == null ? 0 : value + 1;
	}

	public List<Notification> getObjectList(Date serviceDate, String[][] orderBy,
			Object... params) {
	    Session session = sessionFactory.getCurrentSession();
	    Query query = session
	        .createQuery("Select noti FROM  Notification noti Where noti.subjectCode = :subjectCode");
	    query.setParameter("subjectCode", params[0]);
	    return (List<Notification>) query.list();
	}

	public List<Notification> getNotificationListByUserSubject(String userCode,
			int userType) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session
				.createQuery("FROM  Notification Where subjectCode IN (Select Distinct subjectCode From UserSubject Where userCode = :userCode And userType = :userType)");
		query.setParameter("userCode", userCode);
		query.setParameter("userType", userType);
		return (List<Notification>) query.list();
	}
}
